package com.treasure.mall.biz.base;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author allan
 * @date 2019-08-15
 */
@Component
@Slf4j
public class RedisLocker {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public boolean tryLock(String lockKey, String serviceId, long timeout) {
        return redisTemplate.opsForValue().setIfAbsent(lockKey, serviceId, timeout, TimeUnit.SECONDS);
    }

    public boolean release(String lockKey, String serviceId) {
        String scripts = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(scripts, Long.class);

        List<String> keys = Collections.singletonList(lockKey);

        return redisTemplate.execute(redisScript, keys, serviceId) == 1;
    }
}
